package cn.com.xy.sms.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.MatchCacheManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.title.SmsTitleManager;
import cn.com.xy.sms.sdk.util.PopupUtil;
import cn.com.xy.sms.sdk.util.SceneconfigDownloaderQueue;

public class ParseBoxMsgManager {

	public static JSONObject parseMsgForBox(Context ctx, String phoneNumber,
			String smsCenterNum, String smsContent, Map<String, String> extend)
			throws Exception {
		if (ctx == null) {
			throw new Exception(" Context is null.");
		}

		if (phoneNumber == null) {
			throw new Exception(" phoneNumber is null.");
		}
		if (smsContent == null) {
			throw new Exception(" smsContent is null.");
		}

		JSONObject jsonObject = null;
		try {
			Map<String, Object> res = ParseManager.parseMsg(ctx, phoneNumber,
					smsCenterNum, smsContent, 0l, extend);

			if (res != null && ParseBubbleManager.getParseStatu(res) != -1) {
				Map<String, Object> handresult = DexUtil
						.handerBubbleValueMap(res);
				if (handresult == null || handresult.isEmpty())
					return null;

				JSONObject boxObj = DexUtil.handerBoxValueMap(handresult);
				if (boxObj != null && boxObj.length() > 0) {
                    handresult.put("boxJsObj", boxObj);
                }
				
				jsonObject=parseMsgToBubbleResult(handresult, extend);
			}

		} catch (Exception e) {
            /*SDK-536 hewengao/20160713 start*/
            LogManager.e(Constant.TAG, "ParseBoxMsgManager parseMsgForBox",e);
            /*SDK-536 hewengao/20160713 end*/
		}
		return jsonObject;

	}
	
	private static JSONObject parseMsgToBubbleResult(
            Map<String, Object> res, Map<String, String> extend)
            throws Exception {
        try {

            if (res != null) {
                String titleNo = (String) res.get("title_num");
                HashMap<String, String> bubleSmsTitle = SmsTitleManager
                        .getBubleSmsTitle(titleNo);

                boolean bubleSmsTitleIsNotNull = bubleSmsTitle != null
                        && !bubleSmsTitle.isEmpty();

                if (!isNeedRes(extend)
                        || (bubleSmsTitleIsNotNull && PopupUtil.isPopupAble(
                                res, titleNo))) {
                    if (bubleSmsTitle != null) {
                        res.putAll(bubleSmsTitle);
                    }
                    return changeMapToJson(res);
                }
            }

        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "parseMsgToBubbleResult: ", e);

        } finally {
            // 触发情景check队列，情景down队列，资源down队列
            SceneconfigDownloaderQueue.runSceneconfigDownloadQueue();
        }
        return null;
    }
	
	private static boolean isNeedRes(Map<String, String> extend) {
        if (extend == null)
            return true;
        if (!extend.containsKey("isNeedRes"))
            return true;
        String isNeedRes = extend.get("isNeedRes");
        return "true".equalsIgnoreCase(isNeedRes);
    }

    private static JSONObject changeMapToJson(Map<String, Object> handresult) {
        JSONObject jsobj = new JSONObject();
        Set<Entry<String, Object>> set = handresult.entrySet();
        for (Entry<String, Object> entry : set) {
            try {
                jsobj.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {
//                e.printStackTrace();
                LogManager.e(Constant.TAG, "changeMapToJson: ", e);

                return null;
            }
        }
        MatchCacheManager.removeUselessKey(jsobj);
        return jsobj;
    }
    
	 /*SDK-386/songzhirong/2016.04.08---start---*/
	 public static JSONArray parseMsgForCardArray(Context ctx, String phoneNumber, String smsCenterNum, String smsContent, Map<String, String> extend)throws Exception{
		 JSONObject jsonObject = parseMsgForBox(ctx, phoneNumber, smsCenterNum, smsContent, extend);
		 if(jsonObject == null) return null;
		 return DexUtil.parseMsgForCardArray(jsonObject,extend);
		 
	 }
    /*SDK-386/songzhirong/2016.04.08---end---*/

}
